package org.iks.push.business.service;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.pojo.message.ChatMessage;
import org.iks.common.pojo.message.ChatMessageStoreVo;
import org.iks.common.util.JwtUtil;
import org.iks.common.util.ServletUtil;
import org.iks.feign.service.store.SessionRemoteService;
import org.iks.push.business.vo.OnlineUserVo;
import org.iks.push.config.RedisCacheUtil;
import org.iks.push.constant.PushResult;
import org.iks.push.feign.PushFeignRemoteService;
import org.iks.push.session.SessionManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kzou
 * @date 2024/1/3 16:00
 * @description:
 */
@Slf4j
@Service
public class PushService {

    @Autowired
    private PushFeignRemoteService pushFeignRemoteService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SessionRemoteService sessionService;

    /**
     * 消息推送
     *
     * @param chatMessage      消息
     * @return 推送结果
     */
    public PushResult pushMessage(ChatMessage chatMessage) {
        String token = ServletUtil.getToken();
        String account = JwtUtil.getUserAccount(token);
        Channel userChannel = SessionManage.findUserChannel(account);
//        if (userChannel == null) {
//            // 委托给其他实例
////            String address = (String) redisTemplate.opsForValue().get(RedisConstant.onlineServicePrefix + account);
//            OnlineUserVo onlineUserVo = RedisCacheUtil.queryUser(account);
//            String address = onlineUserVo.getServerAddress();
////            log.info("delegate message to {} {}", address, chatMessage);
////            AjaxResult<?> ajaxResult = pushFeignRemoteService.delegateMessage(address, chatMessage);
//            if (ajaxResult.isSuccess()) {
//                return PushResult.SUCCESS;
//            }
//            if (Objects.equals(ajaxResult.getCode(), ResultCode.USER_OFFLINE.getCode())) {
//                log.warn("delegate message error due to target user had offline on server {}", address);
//                return PushResult.NotFound;
//            }
//            log.warn("delegate message error due to rpt exception {}", ajaxResult.getMessage());
//            return PushResult.EXCEPTION;
//        }
        userChannel.writeAndFlush(chatMessage);
        return PushResult.SUCCESS;
    }

    public List<OnlineUserVo> queryOnlineUser() {
        return RedisCacheUtil.queryAll();
    }

    public void sendChatMessage(ChatMessageStoreVo message) {
        log.info("receive message {}", message);
        sessionService.saveChatMessage(message);
    }

}
